#!/usr/bin/perl -w

use File::Path qw(mkpath);
use FindBin;
use Getopt::Long qw(:config pass_through);
use lib $FindBin::Bin;
use strict;
use webkitdirs;

chdirWebKit();

my $os;
my $parts;
my $keep;
my $derivedSourcesSuffix;

my %options = (
    'os=s' => \$os,
    'parts|p=s' => \$parts,
    'keep|k' => \$keep,
    );

GetOptions(%options);

if ($os eq 'orbis') {
    $derivedSourcesSuffix = 'orbis';
} elsif ($os eq 'psp2') {
    $derivedSourcesSuffix = 'psp2';
} else {
    die "Unknown OS: ${os}";
}

if (defined $parts) {
    # disable nuking the DerivedSources_* dir when parts are specified
    $keep = 1;
} else {
    $parts = 'JavaScriptCore,WebCore,WebKit2,WebKitTestRunner';
}

my @parts = split(/,/, $parts);

my $derivedSourcesDir = File::Spec->catdir(getcwd(), "/DerivedSources_${derivedSourcesSuffix}");

if (not defined $keep) {
    system('rm', '-rf', $derivedSourcesDir);
}

foreach (@parts) {
    chdirWebKit();
    if ($_ eq "WebKitTestRunner") {
        # FIXME use same generate-derived-sources-manx.sh script as other parts
        my $webKitTestRunner = File::Spec->catdir($derivedSourcesDir, "WebKitTestRunner");
        mkpath $webKitTestRunner;
        chdir $webKitTestRunner or die;
        system('make', '-f', '../../Tools/WebKitTestRunner/DerivedSources.make', 'WebKitTestRunner=../../Tools/WebKitTestRunner', 'WebCoreScripts=../../Source/WebCore/bindings/scripts');
    } else {
        chdir "Source/$_/gyp" or die;
        system('bash', 'generate-derived-sources-manx.sh', $derivedSourcesDir, $os);
    }
}

chdirWebKit();
chdir 'Source/WebKit/scripts' or die;
system('perl', 'generate-webkitversion.pl', '--config', '../mac/Configurations/Version.xcconfig', '--outputDir', $derivedSourcesDir);
